package com.winkyle.woodenfish.listener;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

/**
 * @author winkyle
 * @date 2018/06/21
 * @description 上拉拉加载监听类
 */
public abstract class PullUpLoadMoreListener extends RecyclerView.OnScrollListener {

    private boolean loading = true;
    int firstVisibleItem, visibleItemCount, totalItemCount;

    private int previousTotal;
    private int currentPage;

    private LinearLayoutManager mLinearLayoutManager;

    public PullUpLoadMoreListener(
            LinearLayoutManager linearLayoutManager) {
        this.mLinearLayoutManager = linearLayoutManager;
        initState();
    }

    /**
     * @description 初始化加载状态
     * @return
     */
    public void initState() {
        this.currentPage = 1;
        this.previousTotal = 0;
    }

    /**
     * @description
     * @param recyclerView
     * @param dx
     * @param dy
     * @return
     */
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        visibleItemCount = recyclerView.getChildCount();
        totalItemCount = mLinearLayoutManager.getItemCount();
        firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();

        if (loading) {
            if (totalItemCount > previousTotal) {
                loading = false;
                previousTotal = totalItemCount;
            }
        }
        if (!loading
                && (totalItemCount - visibleItemCount) <= firstVisibleItem) {
            currentPage++;
            onLoadMore(currentPage);
            loading = true;
        }
    }

    /**
     * @description 上拉时触发加载更多方法
     * @param currentPage 当前页
     * @return
     */
    public abstract void onLoadMore(int currentPage);

}
